package com.zxy.allSearcher.aop;

import com.zxy.allSearcher.annotation.AuthCheck;
import com.zxy.allSearcher.common.ErrorCode;
import com.zxy.allSearcher.exception.BusinessException;
import com.zxy.allSearcher.model.entity.User;
import com.zxy.allSearcher.model.enums.UserRoleEnum;
import com.zxy.allSearcher.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验 AOP
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 对某些需要权限的方法执行拦截
     * 感觉有些逻辑问题，既然某些方法需要指定权限，那权限不存在的错误注解访问，是否应该返回角色定义错误
     * 如果被封号，是跟用户有关，怎么跟方法有关
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 注解上的角色信息
        String mustRole = authCheck.mustRole();
        // 请求对象
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 必须有该权限才通过，如果这个方法存在角色限制
        if (StringUtils.isNotBlank(mustRole)) {
            // 用户角色 vs 方法角色
            UserRoleEnum userRole = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
            UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
            if (mustUserRoleEnum == null || userRole == null) { // 判断方法和用户角色是否合理
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "角色定义错误");
            }
            // 如果被封号，直接拒绝
            if (UserRoleEnum.BAN.getValue().equals(userRole.getValue())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 必须有管理员权限
            if (UserRoleEnum.ADMIN.equals(mustUserRoleEnum) && !mustRole.equals(userRole.getText())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

